package com.lwc.cfdns.pojo.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lwc.cfdns.common.Assert;
import com.lwc.cfdns.enums.ResultCode;
import com.lwc.cfdns.enums.StatusEnum;
import com.lwc.cfdns.pojo.entity.SystemAdmin;
import com.lwc.cfdns.service.SystemAdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 实现SecurityUserDetails对象
 *
 * @author luwc
 * @title SystemAdminDetailServiceImpl
 * @description
 * @time 2023/5/10 17:25:52
 * @version: 1.0
 */
@Component
public class SystemAdminDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SystemAdminService systemAdminService;

    /**
     * 根据用户名查询用户和用户的权限信息
     *
     * @param username
     * @return UserDetails
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/5/11 08:26:32
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息写法一
//        SystemAdmin systemAdmin = systemAdminService.getOne(Wrappers.<SystemAdmin>lambdaQuery().eq(SystemAdmin::getAccount, username));

        // 查询用户信息写法二
        SystemAdmin systemAdmin = systemAdminService.getOne(
                new LambdaQueryWrapper<SystemAdmin>()
                        .eq(SystemAdmin::getUserName, username)
                        .eq(SystemAdmin::getStatus, StatusEnum.NORMAL.getCode())
                        .select(SystemAdmin::getId, SystemAdmin::getAvatar, SystemAdmin::getUserName, SystemAdmin::getPassword, SystemAdmin::getNickName, SystemAdmin::getCreatedAt, SystemAdmin::getStatus, SystemAdmin::getSex, SystemAdmin::getRemark)
        );
        Assert.notNull(systemAdmin, ResultCode.NOT_DATA_FOUNT);

        // 获取用户授权
        List<String> permissions = permissions(systemAdmin.getId());

        // 封装为UserDetails对象
        return new SecuritySystemAdminUserDetails(systemAdmin, permissions);
    }


    /**
     * 当前用户权限
     *
     * @param admin_id
     * @return List<String>
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/5/16 11:41:28
     */
    public List<String> permissions(Long admin_id) {
        List<String> permissions = systemAdminService.getPermissionsByUserId(admin_id);
        // 测试数据
//        ArrayList<String> permissions = new ArrayList<>(Arrays.asList("create-menu", "test"));
        return permissions;
    }
}
